﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

public class TemplateEngine
{
    public string Template { get; set; }

    public Dictionary<string, string> Vars = new Dictionary<string, string>();

    public TemplateEngine(string template)
    {
        Template = template;
        LoadVars();
    }

    private void LoadVars()
    {
        string re1 = ".*?";	// Non-greedy match on filler
        string re2 = "(\\{)";	// Any Single Character 1
        string re3 = "(\\$)";	// Any Single Character 2
        string re4 = "((?:[a-z][a-z]+))";	// Word 1
        string re5 = "(\\})";	// Any Single Character 3

        Regex r = new Regex(re1 + re2 + re3 + re4 + re5, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        MatchCollection matches = r.Matches(Template);
        foreach (Match m in matches)
        {

            if (!Vars.ContainsKey(m.Groups[3].ToString())) Vars.Add(m.Groups[3].ToString(), "");

        }

    }


    public void SetVar(string var, string value)
    {
        try { Vars[var] = value; }
        catch { }
    }

    public override string ToString()
    {
        try
        {
            string outstring = Template;
            foreach (var v in Vars)
            {
                //if (v.Value == "") throw new Exception("Unused Template Variables");

                outstring = outstring.Replace("{$" + v.Key + "}", v.Value);
            }
            return outstring;
        }
        catch (Exception e)
        {
            return "";
        }
    }


}

